<template>
  <div style="padding: 20px;">
    <el-form ref="article" label-width="80px" :model="articleForm" :rules="rules">
      <!-- 文章标题 -->
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="articleForm.title" />
      </el-form-item>
      <!-- 文章封面 -->
      <el-form-item label="文章封面" prop="cover">
        <el-upload
          ref="upload"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :limit="1"
          :http-request="upload"
          :before-upload="check"
          :on-change="addPrompt"
          :file-list="imgList"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img :src="file.url" class="el-upload-list__item-thumbnail" alt="">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in" />
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                <i class="el-icon-download" />
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
      <!-- 文章内容 -->
      <el-form-item prop="content">
        <div style="border: 1px solid #ccc;">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :default-config="toolbarConfig"
            :mode="mode"
          />
          <Editor
            v-model="articleForm.content"
            style="height: 500px; overflow-y: hidden;"
            :default-config="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <div class="submit">
      <el-button @click="submita">提交</el-button>
      <el-button @click="$router.back()">返回</el-button>
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadImgCover, uploadArticle, getNewDetail, updateNew } from '@/api/news.js'
export default {
  components: { Editor, Toolbar },
  props: {
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      articleForm: {
        title: '',
        cover: '',
        content: ''
      },
      editor: null,
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple',
      disabled: false,
      imgFile: null,
      imgUpSucess: false,
      // 缓存id
      cacheId: '',
      imgList: [],
      rules: {
        title: [
          { required: true, message: '请输入文章题目', trigger: 'blur' }
        ],
        cover: [
          {
            trigger: 'blur', validator: (rule, value, callback) => {
              if (this.imgUpSucess || this.type === 'edit') {
                console.log('校验到底通过了吗啊？')
                callback()
              } else {
                callback(new Error('请上传文章封面'))
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  watch: {
    id: {
      deep: true,
      immediate: true,
      handler(val) {
        this.type === 'edit' &&
          !!val &&
          val !== this.cacheId &&
          (this.cacheId = val) &&
          this.getDetailNew()
      }
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    // 通过id获取数据
    async getDetailNew() {
      try {
        const { data: { title, cover, content, _id }} = await getNewDetail(this.id)
        this.articleForm = { title, cover, content }
        this.imgList.push({ name: _id, url: cover })
        console.log(this.articleForm)
      } catch (error) {
        console.log(error)
      }
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    // 文件上到服务器
    async upload() {
      try {
        const res = await uploadImgCover(this.imgFile)
        if (res.code === 20000) {
          this.articleForm.cover = res.data.imgUrl
          this.updateArticle()
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 文件上传到页面时进行校验
    check(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = ['jpg', 'png', 'jpeg']
      if (!suffix.includes(fileSuffix)) {
        this.$message({
          type: 'error',
          message: '图片类型为 jpg png jpeg'
        })
        return false
      }
      if (fileSuffix.size / 1024 > 500) {
        this.$message({
          type: 'error',
          message: '图片大小不得超过500kb'
        })
        return false
      }
      try {
        const formData = new FormData()
        formData.append('files', file)
        this.imgFile = formData
      } catch (error) {
        console.log(error)
      }
    },
    // 删除添加的图片
    handleRemove() {
      this.$refs.upload.clearFiles()
      this.imgUpSucess = false
      this.imgList = []
      this.articleForm.cover = ''
    },
    // 上传文章
    submita() {
      this.$refs.article.validate((valid) => {
        if (valid) {
          if (this.imgUpSucess) {
            this.$refs.upload.submit()
          }
          if (!this.imgUpSucess && this.type === 'edit') {
            this.updateArticle()
          }
        } else {
          return false
        }
      })
    },
    // 添加图片成功提示
    addPrompt() {
      this.$message({
        type: 'success',
        message: '图片添加成功'
      })
      this.imgUpSucess = true
    },
    // 上传文章
    async updateArticle() {
      if (this.id && this.type === 'edit') {
        const res = await updateNew(this.id, this.articleForm)
        console.log(res)
        if (res.code === 20000) {
          this.articleForm = {
            title: '',
            cover: '',
            content: ''
          }
          this.$message({
            type: 'success',
            message: res.message
          })
          this.imgUpSucess = false
          this.handleRemove()
          this.$router.back()
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      } else {
        const res = await uploadArticle(this.articleForm)
        console.log(res)
        if (res.code === 20000) {
          this.articleForm = {
            title: '',
            cover: '',
            content: ''
          }
          this.$message({
            type: 'success',
            message: res.message
          })
          this.imgUpSucess = false
          this.handleRemove()
          this.$router.back()
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
